<template>
  <el-dialog v-model="uploadOpen" title="添加数据" width="760px" @open="initOpen" @close="closeUpload">
    <el-form :model="uploadForm" ref="uploadFormRef" :rules="uploadFormRules" label-width="100px">
      <el-form-item label="数据范围：" prop="dataRange" class="data-range">
        <el-select v-model="uploadForm.provinceId" placeholder="请选择省" @change="chooseProvince" clearable>
          <el-option v-for="item in provinceData" :key="item.id" :label="item.name" :value="item.id">
          </el-option>
        </el-select>
        <el-select v-model="uploadForm.cityId" placeholder="请选择市" @change="chooseCity" clearable>
          <el-option v-for="item in cityData" :key="item.id" :label="item.name" :value="item.id">
          </el-option>
        </el-select>
        <el-select v-model="uploadForm.countyId" placeholder="请选择区县" @change="chooseCounty" clearable>
          <el-option v-for="item in areaData" :key="item.id" :label="item.name" :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="数据类别：" prop="typeCode">
        <el-select v-model="uploadForm.type" @change="changeType" clearable>
          <el-option v-for="item in codeOption" :key="item.dictItemCode" :label="item.dictItemName"
            :value="item.dictItemCode"></el-option>
        </el-select>
        <el-select v-model="uploadForm.typeCode" placeholder="请选择" @change="codeTypeSelect" clearable>
          <el-option v-for="item in codeTypeOption" :key="item.dictItemCode" :label="item.dictItemName"
            :value="item.dictItemCode" />
        </el-select>
      </el-form-item>
      <el-form-item label="数据文件：" prop="fileIds">
        <file-upload v-model="uploadForm.fileList" :limit="1000" uploadUrl="/attachment/uploadShpFile"
          downloadUrl="/attachment/downLoadShpFile" @uploadFile="uploadSuccess" @delFile="delFile"></file-upload>
      </el-form-item>
      <el-form-item label="上传人：" prop="uploadUser">
        <span>{{ uploadForm.uploadUser }}</span>
      </el-form-item>
      <el-form-item label="上传日期：" prop="uploadTime">
        <span>{{ uploadForm.uploadTime }}</span>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button type="primary" @click="saveUpload">保存</el-button>
      <el-button plain @click="resetUpload">清空</el-button>
      <el-button plain @click="closeUpload">取消</el-button>
    </template>
  </el-dialog>
  <!-- 上传后表格 -->
  <el-collapse-transition>
    <vue-drag-resize :isActive="true" :isDraggable="false" :sticks="['tm']" v-if="isShowList" class="upload-table"
      :h="480" :preventActiveBehavior="true">
      <el-card>
        <p>
          <el-row :gutter="10" justify="space-between">
            <el-col :span="21" class="form-name">{{ fromName }}</el-col>
            <el-col :span="1.5">
              <el-button type="primary" @click="saveList">确定</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button plain @click="closeTable">关闭</el-button>
            </el-col>
          </el-row>
        </p>
        <el-table v-loading="uploadTableLoading" :data="uploadTable.slice((page-1)*rows, page*rows)" :border="true" stripe>
          <el-table-column v-for="item in uploadTableName" :key="item" :label="item.name" :prop="item.title"
            align="center" :min-width="minWidthSet(item.name)">
            <template #default="{ row }" v-if="item.title.indexOf('Aiid') > 0">
              <el-button type="text" v-if="row[item.title + 'Id']" @click="uploadFiles(row, item.title)">编辑</el-button>
              <el-button type="text" v-else @click="uploadFiles(row, item.title)">上传</el-button>
            </template>
            <template #default="{ row }" v-else-if="/Arwid|Acid|Arid/.test(item.title)">
              <el-button type="text" v-if="row[item.title+'Id']" @click="uploadFiles(row, item.title)">编辑</el-button>
              <el-button type="text" v-else @click="uploadFiles(row, item.title)">上传</el-button>
            </template>
            <template #default="{ row }" v-if="checkDict(item.title, codeType)">
              <dict-tag :value="row[item.title]" :code="checkDict(item.title, codeType)"></dict-tag>
            </template>
          </el-table-column>
        </el-table>
        <pagination style="margin-top: 15px" v-show="uploadTable.length > 0" :total="uploadTable.length" v-model:page="page"
              v-model:limit="rows" :pageSizes="[5,10,20]"/>
      </el-card>
    </vue-drag-resize>
  </el-collapse-transition>
  <UploadFiles v-model:open="openImage" :file="file" :type="uploadType" @updateTable="updateTable" />
</template>
<script setup>
import { getProvince, getChildArea } from "@/api/system/division"
import { useNow, useDateFormat } from '@vueuse/core'
import { getDict } from '@/api/system/dict'
import { parseShp, exist, updateAll } from '@/api/businessManage/dataLoader/spatialData'
import UploadFiles from './uploadFiles.vue'
import { checkDict } from '@/views/businessManage/common/dict.js'
import { minWidthSet } from '@/views/businessManage/common/minWidth'
import { getDetailId } from '@/views/businessManage/common/formDetail'

const props = defineProps({
  uploadOpen: Boolean
})
const emits = defineEmits(['update:uploadOpen', 'selectIServerId', 'setIServerName'])
const { proxy } = getCurrentInstance()
const route = useRoute()

const uploadData = reactive({
  provinceData: [],
  cityData: [],
  areaData: [],
  fromName: '',
  uploadTable: [],
  uploadTableName: {},
  uploadTableLoading: false,
  isShowList: false,
  codeTypeOption: [],
  codeOption: []
})
const uploadFormInit = () => {
  return {
    dataRange: [],
    uploadUser: localStorage.getItem('userName'),
    uploadTime: useDateFormat(useNow(), 'YYYY-MM-DD').value
  }
}

const { provinceData, cityData, areaData, fromName, uploadTable, uploadTableName, uploadTableLoading, isShowList, codeTypeOption, codeOption } = toRefs(uploadData)
const uploadForm = reactive(uploadFormInit())
const dataRangeValidate = (rule, value, cb) => {
  if (uploadForm.province && uploadForm.city) {
    cb()
  } else {
    cb(new Error('请将数据范围填写完整！'))
  }
}
const closeTable = () => {
  isShowList.value = false
  emits('selectIServerId', [])
}
const uploadFormRules = reactive({
  dataRange: [
    { required: true, message: '请选择数据范围！', trigger: 'change' },
    { validator: dataRangeValidate, trigger: 'change' }
  ],
  typeCode: [{ required: true, message: '请选择数据类别！', trigger: 'change' }],
  fileIds: [{ required: true, message: '请上传数据文件！', trigger: 'change' }],
})
const initOpen = () => {
  // resetUpload()
  getProvinceData()
  getType()
  nextTick(() => {
    proxy.$refs['uploadFormRef'].clearValidate()
  })
}
const getProvinceData = () => {
  getProvince().then(res => {
    if (res.code == 200) {
      provinceData.value = res.data
    }
  })
}
const chooseProvince = (value) => {
  uploadForm.province = provinceData.value.find(item => item.id == value)?.name
  uploadForm.cityId = null
  uploadForm.countyId = null
  cityData.value = []
  areaData.value = []
  getChildArea(value).then(response => {
    cityData.value = response.data
  })
  uploadForm.dataRange.push(value)
}
const chooseCity = (value) => {
  uploadForm.city = cityData.value.find(item => item.id == value)?.name
  uploadForm.countyId = null
  areaData.value = []
  getChildArea(value).then(response => {
    areaData.value = response.data
  })
  uploadForm.dataRange.push(value)
}
const chooseCounty = (value) => {
  uploadForm.county = areaData.value.find(item => item.id == value)?.name
  uploadForm.dataRange.push(value)
}
const getType = () => {
  getDict('Space').then(res => {
    codeOption.value = res.data
  })
}
const changeType = (value) => {
  codeTypeOption.value = []
  getDict(value).then(res => {
    codeTypeOption.value = res.data
  })
}
const codeType = ref('')
const codeTypeSelect = (value) => {
  codeType.value = value
}
const saveUpload = () => {
  proxy.$refs['uploadFormRef'].validate(async (valid, fields) => {
    if (valid) {
      const { province, city, county } = uploadForm
      let res = await exist(codeType.value, { province, city, county, smId: route.query.id })
      let iServerName = codeTypeOption.value.find(item => item.dictItemCode == uploadForm.typeCode)?.description
      if (res.data == '1') {
        proxy.$modal.confirm('该省市区（县）已有该数据，是否进行覆盖？').then(function () {
          return parseShp({ ...uploadForm, smId: route.query.id })
        }).then(res => {
          proxy.$modal.msgSuccess('覆盖成功！')
          uploadTable.value = res.data.list
          uploadTableName.value = res.data.titleAndNameVOS
          fromName.value = res.data.fromName
          if (uploadTable.value.length > 0) { isShowList.value = true }
          emits('update:uploadOpen', false)
          emits('setIServerName', iServerName)
          emits('selectIServerId', res.data.list)
          uploadTableLoading.value = false
          resetUpload()
        })
      } else {
        uploadTableLoading.value = true
        parseShp({ ...uploadForm, smId: route.query.id }).then(res => {
          uploadTable.value = res.data.list
          uploadTableName.value = res.data.titleAndNameVOS
          fromName.value = res.data.fromName
          if (uploadTable.value.length > 0) { isShowList.value = true }
          emits('update:uploadOpen', false)
          emits('setIServerName', iServerName)
          emits('selectIServerId', res.data.list)
          uploadTableLoading.value = false
          resetUpload()
        })
      }
    } else {
      proxy.$refs['uploadFormRef'].scrollToField(Object.keys(fields)[0])
    }
  })
}
const resetUpload = () => {
  proxy.resetAllForm(uploadForm, uploadFormInit())
}
const closeUpload = () => {
  emits('update:uploadOpen', false)
}
const uploadSuccess = (files) => {
  uploadForm.fileIds = files.map(item => item.attachId).join(',')
  uploadForm.fileList = files
  proxy.$refs['uploadFormRef'].clearValidate()
}
const delFile = files => {
  uploadForm.fileIds = files.map(item => item.attachId).join(',')
}
const saveList = () => {
  updateAll(codeType.value, uploadTable.value).then(res => {
    proxy.$modal.msgSuccess('保存成功！')
    isShowList.value = false
  })
}

const openImage = ref(false)
const uploadType = ref()
const idName = ref()
const curTableItem = ref()
const curTableItemName = ref()
const file = ref([])
const uploadFiles = (row, name) => {
  openImage.value = true
  uploadType.value = name.indexOf('Aiid') > 0 ? 'image' : 'file'
  idName.value = getDetailId(codeType.value)
  curTableItem.value = row[idName.value]
  curTableItemName.value = name
  file.value = uploadTable.value.find(item => item[idName.value] == curTableItem.value)[name + 'Name'] || []
}
const updateTable = (files) => {
  uploadTable.value = uploadTable.value.map(item => {
    if (item[idName.value] == curTableItem.value) {
      item[curTableItemName.value + 'Id'] = files.map(fileItem => fileItem.attachId).join(',')
      item[curTableItemName.value + 'Name'] = files
    }
    return item
  })
}

const page = ref(1)
const rows = ref(5)
const changePagination = (val) => {
  console.log(val)
}

defineExpose({
  isShowList
})
</script>
<style scoped lang="scss">
.upload-table {
  position: absolute;
  bottom: 5px !important;
  width: calc(100% - 10px);
  z-index: 10 !important;
  margin: 0 5px;
  top: unset !important;
  max-height: 90%;

  :deep(.content-container) {
    width: 100% !important;
    max-height: 100%;

    .el-card,
    .el-card__body {
      height: 100%;

      .el-scrollbar {
        overflow: auto;
      }
    }
  }
}

.data-range {
  .el-select {
    width: 140px;
  }
}

.el-select:not(:last-child) {
  margin-right: 10px;
}

.form-name {
  font-weight: bold;
}
</style>